//
//  AMPMineViewController.swift
//  LivingHelper
//
//  Created by Ampaw on 2017/9/8.
//  Copyright © 2017年 Ampaw. All rights reserved.
//

import UIKit

/// cell数据源
private let cellDataArray = [
                              [["title":"收藏","image":"center_cell_ collect"],// 第一组
                               ["title":"分享","image":"center_cell_share"]],
                              [["title":"设置","image":"center_cell_setting"], // 第二组
                               ["title":"关于","image":"center_cell_about"]]
                            ]

/// HeadView高度
private let kHeadViewHeight: CGFloat = 240

class AMPMineViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    var tableView:UITableView!
    var headerBg:UIImageView?
    var headerIcon:UIImageView?
    
    var navView:UIView? // 自定义导航条的View
    

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = AMPConstants.AMPBGViewColor
        self.edgesForExtendedLayout = UIRectEdge()
        self.extendedLayoutIncludesOpaqueBars = false
        self.modalPresentationCapturesStatusBarAppearance = false
        self.automaticallyAdjustsScrollViewInsets = true
        
        // 准备UI
        setUpUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 隐藏导航条
        self.isDidIconImg = false
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 显示导航条
        if self.isDidIconImg == false {
            self.navigationController?.setNavigationBarHidden(false, animated: true)
        }
    }
    
    // MARK: - 准备UI
    func setUpUI() {
        createHeaderView()
        createTableView()
        createNavBar()
    }
    
    // 创建 HeadView
    func createHeaderView() {
        unowned let WS = self
        
        // 背景图
        headerBg = UIImageView(frame: CGRect(x: 0, y: -kHeadViewHeight, width: AMPConstants.AMP_SCREEN_WIDTH, height: kHeadViewHeight))
        headerBg?.backgroundColor = AMPConstants.AMPYellowColor
        headerBg?.image = UIImage(named: "")
        headerBg?.isUserInteractionEnabled = true
        
        // 头像
        headerIcon = UIImageView()
        headerIcon?.layer.cornerRadius = AMPConstants.AMP_SCREEN_WIDTH/8
        headerIcon?.layer.masksToBounds = true
        headerIcon?.layer.borderColor = UIColor.white.cgColor
        headerIcon?.layer.borderWidth = 1.5
        headerIcon?.image = UIImage(named: "img_default")
        headerIcon?.backgroundColor = UIColor.clear
        headerBg?.addSubview(headerIcon!)
        
        // 给头像添加手势
        let tapGes = UITapGestureRecognizer(target: self, action: #selector(loginOrRegistAction))
        headerIcon?.isUserInteractionEnabled = true
        headerIcon?.addGestureRecognizer(tapGes)
        
        // 给头像添加约束
        headerIcon?.snp.makeConstraints({ (make) -> Void in
            make.width.equalTo(AMPConstants.AMP_SCREEN_WIDTH/4)
            make.height.equalTo(AMPConstants.AMP_SCREEN_WIDTH/4)
            make.left.equalTo(WS.headerBg!).offset(AMPConstants.AMP_SCREEN_WIDTH/2 - AMPConstants.AMP_SCREEN_WIDTH/8)
            make.top.equalTo(WS.headerBg!).offset(80)
        })
    }
    
    // 创建 TableView
    func createTableView() {
        self.tableView = UITableView(frame: self.view.frame, style: UITableViewStyle.grouped)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.contentInset = UIEdgeInsetsMake(kHeadViewHeight, 0, 0, 0)
        self.tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "mineCell")
        self.tableView.backgroundColor = AMPConstants.AMPBGViewColor
        self.tableView.tableFooterView = UIView()
        self.tableView.addSubview(headerBg!)
        self.view.addSubview(self.tableView)
    }
    
    // 创建 自定义导航条
    func createNavBar() {
        navView = UIView()
        navView?.backgroundColor = AMPConstants.AMPMainColor
        navView?.alpha = 0
        self.view.addSubview(navView!)
        
        navView?.snp.makeConstraints({ (make) -> Void in
            make.width.equalTo(AMPConstants.AMP_SCREEN_WIDTH)
            make.height.equalTo(64)
            make.top.equalTo(0)
        })
        
        let title = UILabel()
        title.font = UIFont.systemFont(ofSize: 18)
        title.textColor = UIColor.white
        title.text = "我的"
        title.textAlignment = NSTextAlignment.center
        navView?.addSubview(title)
        
        unowned let WS = self
        title.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(WS.navView!).offset(20)
            make.height.equalTo(44)
            make.width.equalTo(AMPConstants.AMP_SCREEN_WIDTH)
        }
        
    }
    
    // MARK: - Event
    func loginOrRegistAction(){
//        print(#function)
        self.isDidIconImg = true
        let loginVC = AMPLoginViewController()
        let nav = UINavigationController.init(rootViewController: loginVC)
        self.present(nav, animated: true, completion: nil)
        /*
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(loginVC, animated: true)
        self.hidesBottomBarWhenPushed = false
 */
    }
    
    // MARK: - UITableViewDelegate,UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellDataArray[section].count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return cellDataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mineCell", for: indexPath)
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator  // 设置Cell右边显示 “箭头”
        cell.selectionStyle = UITableViewCellSelectionStyle.none // 设置选中Cell样式为“无效果”
        
        // Cell图标
        var icon: UIImageView? = cell.viewWithTag(1000) as? UIImageView
        if icon == nil {
            icon = UIImageView()
            icon?.tag = 1000
            cell.contentView.addSubview(icon!)
            icon?.snp.makeConstraints({ (make) -> Void in
                make.width.equalTo(20)
                make.height.equalTo(20)
                make.left.equalTo(cell.contentView).offset(16)
                make.top.equalTo(cell.contentView).offset(12)
            })
        }
        
        // Cell标题
        var title: UILabel? = cell.viewWithTag(2000) as? UILabel
        if title == nil {
            title = UILabel()
            title?.tag = 2000
            title?.textColor = AMPConstants.AMPMainTextColor
            title?.font = UIFont.systemFont(ofSize: 15)
            cell.contentView.addSubview(title!)
            title?.snp.makeConstraints({ (make) -> Void in
                make.height.equalTo(44)
                make.left.equalTo(cell.contentView).offset(46)
                make.right.equalTo(cell.contentView).offset(0)
                make.top.equalTo(cell.contentView).offset(0)
            })
        }
        
        // 为Cell赋值
        let array = cellDataArray[(indexPath as NSIndexPath).section]
        icon?.image = UIImage(named: array[(indexPath as NSIndexPath).row]["image"]!)
        title?.text = array[(indexPath as NSIndexPath).row]["title"]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if (indexPath as NSIndexPath).section == 0 {    // 第0组
            if (indexPath as NSIndexPath).row == 0 {
                let collectVC = AMPCollectViewController()
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(collectVC, animated: true)
                self.hidesBottomBarWhenPushed = false
            }else if (indexPath as NSIndexPath).row == 1 {
                let shareVC = AMPShareViewController()
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(shareVC, animated: true)
                self.hidesBottomBarWhenPushed = false
            }
        }else if (indexPath as NSIndexPath).section == 1 { // 第1组
            if (indexPath as NSIndexPath).row == 0 {
                let settingVC = AMPSettingViewController()
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(settingVC, animated: true)
                self.hidesBottomBarWhenPushed = false
            }else if (indexPath as NSIndexPath).row == 1 {
                let aboutVC = AMPAboutViewController()
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(aboutVC, animated: true)
                self.hidesBottomBarWhenPushed = false
            }
        }
    }
    
    // MARK: - UIScrollView Delegate
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        /**
         *  通过滚动视图获取到滚动偏移量从而去改变图片的变化
         */
        let yOffset = scrollView.contentOffset.y
        let xOffset = (yOffset + kHeadViewHeight)/2
        
        if yOffset > -kHeadViewHeight {
            //上拉
            var ap = 1 - fabs(yOffset+100)/CGFloat(140)
            
            if ap > 1 {
                ap = 1
            }
            navView?.alpha = ap
        }else{
            
            navView?.alpha = 0
        }
        
        if yOffset < -kHeadViewHeight {
            
            var rect = headerBg?.frame
            rect?.origin.y = yOffset
            rect?.size.height = -yOffset
            rect?.origin.x = xOffset
            rect?.size.width = AMPConstants.AMP_SCREEN_WIDTH + fabs(xOffset)*2
            headerBg?.frame = rect!
            
            headerIcon?.snp.updateConstraints({ (make) -> Void in
                make.left.equalTo(((rect?.width)! - AMPConstants.AMP_SCREEN_WIDTH/4)/2)
            })
        }
        
    }
    
    // MARK: - 懒加载
    /// 设置判断是否点击的是 头像Icon，用来控制导航条的显示与隐藏
    lazy var isDidIconImg: Bool = {
        let isDidIconImg = false
        
        return isDidIconImg
    }()
    
}
